package com.infore.maintenance.main.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.infore.common.base.EppPage;
import com.infore.common.base.Msg;
import com.infore.common.base.ResultUtil;
import com.infore.common.base.WrapperHelp;
import com.infore.common.constants.DataStatConstants;
import com.infore.common.fw.BaseController;
import com.infore.common.model.dto.TBaseDatasourceSaveDto;
import com.infore.common.model.entity.TBaseDatasource;
import com.infore.common.model.entity.vo.TBaseDatasourceVo;
import com.infore.common.response.ApiListResponse;
import com.infore.common.response.ApiResponse;
import com.infore.common.utils.EncryptAESUtil;
import com.infore.maintenance.main.service.TBaseDatasourceService;
import com.infore.metadata.core.model.TableModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


/**
 * <p>
 * 数据源 前端控制器
 * </p>
 *
 * @author lijh
 * @since 2022-12-20
 */
@RestController
@Api(value = "数据源前端控制器", tags = "数据源前端控制器")
@RequestMapping("/tBaseDatasource")
public class TBaseDatasourceController extends BaseController {
	private String prefix = "/tBaseDatasource";

	@Autowired
	private TBaseDatasourceService TBaseDatasourceService;

	@GetMapping()
	public String TBaseDatasourceController(){
		return prefix;
	}

	/**
	 * 查询数据源列表
	 * @param tbasedatasourceVo 数据源的vo类
	 * @return Msg<Object> 结果集
	 * @author lijh
	 * @since 2022-12-20
	 */
	@PostMapping("/list")
	@ResponseBody
	@ApiOperation(value = "查询数据源列表", notes = "数据源列表查询 ")
	public Msg<Object> list(TBaseDatasourceVo tbasedatasourceVo){
		//sql查询条件
		Wrapper<TBaseDatasource> wrapper = null ;
		try {
			wrapper = (Wrapper<TBaseDatasource>) WrapperHelp.addCondition(new EntityWrapper<TBaseDatasource>(), tbasedatasourceVo);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.error(500,e.getMessage());
		}
		//查询方法
		Page<TBaseDatasource> eppPage = new EppPage<TBaseDatasource>(TBaseDatasourceService,tbasedatasourceVo,wrapper);
		Page<TBaseDatasource> page = TBaseDatasourceService.selectPage(eppPage, wrapper);
		return ResultUtil.successPage(page);
	}

	/**
	 * 查询数据源列表
	 * @param tBaseDatasourceSaveDto 数据源
	 * @return Msg<Object> 结果集
	 * @author lijh
	 * @since 2022-12-20
	 */
	@ResponseBody
	@ApiOperation(value = "添加数据源", notes = "数据源新增")
	@RequestMapping(value="/add",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	public Msg<Object> add(@RequestBody TBaseDatasourceSaveDto tBaseDatasourceSaveDto){

		Wrapper<TBaseDatasource> wrapper = new  EntityWrapper<TBaseDatasource>();
		wrapper.eq("database_code", tBaseDatasourceSaveDto.getDatabaseCode());
		List<TBaseDatasource> entityList = TBaseDatasourceService.selectList(wrapper);
		if(entityList.size()>0) {
			return ResultUtil.error("重复添加");
		}

		TBaseDatasource tbasedatasource = new TBaseDatasource();
		BeanUtil.copyProperties(tBaseDatasourceSaveDto,tbasedatasource);

		//校验数据库连接
		TBaseDatasourceService.getDatabaseConnect(tbasedatasource);
		//密码加密
		String enPassword = null;
		try {
			enPassword = EncryptAESUtil.aesEncrypt(tBaseDatasourceSaveDto.getJdbcPassword(),DataStatConstants.AES_KEY_PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
		tbasedatasource.setJdbcPassword(enPassword);
		tbasedatasource.setCreateTime(new Date());
		tbasedatasource.setCreateUserid("");
		tbasedatasource.setDelState(0);
		//插入数据
		boolean flag = TBaseDatasourceService.insert(tbasedatasource);
		return ResultUtil.setResult(flag,tbasedatasource.getDatabaseCode());
	}


	/**
	  * 更新数据源方法
	  *
	  * @param tbasedatasource 数据源
	  * @return Msg<Object>
	  * @author lijh
	  * @since 2022-12-20
	  */
	@ResponseBody
	@ApiOperation(value = "更新数据源", notes = "数据源更新")
	@RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public Msg<Object> edit(@RequestBody TBaseDatasource tbasedatasource) {

		//旧数据
		TBaseDatasource sourceDataSource = TBaseDatasourceService.selectById(tbasedatasource.getId());
		String enPassword = null;
		try {
			enPassword = EncryptAESUtil.aesEncrypt(tbasedatasource.getJdbcPassword(),DataStatConstants.AES_KEY_PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
		tbasedatasource.setJdbcPassword(enPassword);
		tbasedatasource.setCreateUserid(sourceDataSource.getCreateUserid());
		tbasedatasource.setCreateTime(new Date());
		//插入数据
		boolean flag = TBaseDatasourceService.updateById(tbasedatasource);
		return ResultUtil.setResult(flag, tbasedatasource.getDatabaseCode());
	}

	/**
	 * 删除数据源
	 *
	 * @param  id
	 * @return Msg<Object>
	 * @author lijh
	 * @since 2022-12-20
	 */
	@RequestMapping(value = "/del", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "删除数据源-逻辑删除", notes = "删除数据源-逻辑删除")
	public Msg<Object> del(String id) {

		TBaseDatasource dataSource = TBaseDatasourceService.selectById(id);
		dataSource.setDelState(1);
		boolean flag = TBaseDatasourceService.updateById(dataSource);
//		Map<String, Object> columnMap = new HashMap<String, Object>();
//		columnMap.put("id", id);
//		boolean flag = TBaseDatasourceService.deleteByMap(columnMap);
		return ResultUtil.setResult(flag);
	}


	@GetMapping("/checkDatabaseConnect")
	@ResponseBody
	@ApiOperation(value = "校验数据源连接", notes = "校验数据源连接")
	public ApiResponse checkDatabaseConnect(TBaseDatasource tbasedatasource) {
		TBaseDatasourceService.getDatabaseConnect(tbasedatasource);
		return ApiResponse.ok();
	}



	@GetMapping("/queryDatasource")
	@ResponseBody
	@ApiOperation(value = "查询各数据源中的表（树形结构）", notes = "查询各数据源中的表（树形结构）")
	public ApiListResponse queryDatasource(@RequestParam(name = "tableName",required = false) String  tableName) {
		return ApiListResponse.ok(TBaseDatasourceService.getDatasourcesGroupByDatabaseType(tableName));
	}


	@GetMapping("/queryDatasourceTables")
	@ResponseBody
	@ApiOperation(value = "查询各数据源中表的列信息（树形结构）", notes = "查询各数据源中表的列信息（树形结构）")
	public ApiListResponse queryDatasourceAllTables(@RequestParam(name = "tableName",required = false) String  tableName) {
		return ApiListResponse.ok(TBaseDatasourceService.getDatasourcesAllTableInfo(tableName));
	}



	@GetMapping("/queryTablesColumns")
	@ResponseBody
	@ApiOperation(value = "查询表的列信息", notes = "查询表的列信息")
	public ApiListResponse<TableModel> queryTablesColumns(@RequestParam(name = "databaseCode") String  databaseCode,
														  @RequestParam(name = "tableName",required = false) String  tableName) {
		return ApiListResponse.ok(TBaseDatasourceService.getTablesColumns(databaseCode,tableName));
	}

}
